package renguanyu.app.auth4fx.view.role;

import javafx.beans.property.*;
import javafx.beans.value.ChangeListener;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.geometry.Insets;
import javafx.scene.control.*;
import javafx.scene.control.cell.CheckBoxTableCell;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.VBox;
import renguanyu.app.auth4fx.App;
import renguanyu.app.auth4fx.controller.role.RoleInfoDeleteController;
import renguanyu.app.auth4fx.controller.role.RoleListQueryController;
import renguanyu.app.auth4fx.model.role.RoleVo;
import renguanyu.app.auth4fx.util.NotificationUtil;

import java.util.List;


public class RoleListView extends VBox {

    private HBox operatePane;
    private HBox searchPane;
    private HBox dataPane;
    private HBox pagePane;
    public RoleListView() {
        operatePane = createOperatePane();// 操作栏
        searchPane = createSearchPane();// 搜索栏
        dataPane = createDataPane();// 数据表格
        pagePane = createPagePane();// 分页
        super.getChildren().addAll(operatePane, searchPane, dataPane, pagePane);// 组装
        super.setPadding(new Insets(15));
        new RoleListQueryController(this).startAsyncQuery();// 初始化时加载数据
    }

    public static RoleVo selectedRole;
    public List<RoleVo> selectedRoleList;
    private HBox createOperatePane() {
        Button addButton = new Button("新增");
        Button updateButton = new Button("修改");
        Button deleteButton = new Button("删除");
        Button permissionButton = new Button("分配权限");

        addButton.setOnAction(e-> App.mainView.setCenter(new RoleInfoSaveView()));
        updateButton.setOnAction(
            e-> {
                List<RoleVo> roleVoList = RoleTableView.getItems().stream().filter(item -> item.isSelected()).toList();
                System.out.println("roleVoList = " + roleVoList);
                if(roleVoList.size()!=1){
                    NotificationUtil.show("修改时，必须选择一条记录，否则无法执行修改操作。");
                    return;
                }
                selectedRole = roleVoList.get(0);
                App.mainView.setCenter(new RoleInfoUpdateView(this));
            }
        );
        deleteButton.setOnAction(
            e -> {
                List<RoleVo> RoleList = RoleTableView.getItems().stream().filter(item -> item.isSelected()).toList();
                System.out.println("RoleList = " + RoleList);
                if(RoleList.size()<1){
                    NotificationUtil.show("删除时，必须选择大于或等于一条的记录，否则无法执行删除操作。");
                    return;
                }
                selectedRoleList = RoleList;
                new RoleInfoDeleteController(this).execute();
            }
        );
        permissionButton.setOnAction(event -> {
            System.out.println("click permissionButton");
            List<RoleVo> roleVoList = RoleTableView.getItems().stream().filter(item -> item.isSelected()).toList();
            if(roleVoList.size()!=1){
                NotificationUtil.show("分配权限时，必须选择一条记录，否则无法执行分配操作。");
                return;
            }
            selectedRole = roleVoList.get(0);
            App.mainView.setCenter(new RolePermissionListView());
        });

        HBox operateBar = new HBox(10, addButton, updateButton,deleteButton,permissionButton);
        operateBar.setPadding(new Insets(0, 0, 10, 0));
        return operateBar;
    }

    public StringProperty searchFieldKey = new SimpleStringProperty();
    public StringProperty searchFieldValue = new SimpleStringProperty();
    private HBox createSearchPane() {
        ComboBox<String> searchFieldComboBox = new ComboBox<>();
        searchFieldComboBox.getItems().addAll("角色名", "密码");
        searchFieldComboBox.valueProperty().bindBidirectional(searchFieldKey);
        searchFieldComboBox.getSelectionModel().selectFirst();
        TextField searchFieldContent = new TextField();
        searchFieldContent.textProperty().bindBidirectional(searchFieldValue);
        searchFieldContent.setOnAction(e -> new RoleListQueryController(this).startAsyncQuery());
        HBox.setHgrow(searchFieldContent, Priority.ALWAYS);
        Button searchButton = new Button("搜索");
        searchButton.setOnAction(e -> new RoleListQueryController(this).startAsyncQuery());
        HBox searchBar = new HBox(10, searchFieldComboBox, searchFieldContent, searchButton);
        searchBar.setPadding(new Insets(0, 0, 10, 0));
        return searchBar;
    }

    private StringProperty dataPaneStatusText = new SimpleStringProperty();
    public void dataPaneStatusLoading() {
        dataPaneStatusText.set("加载中");
    }
    public void dataPaneStatusHaveData() {
        dataPaneStatusText.set("有数据");
    }
    public void dataPaneStatusNoData() {
        dataPaneStatusText.set("无数据");
    }
    public void dataPaneStatusError() {
        dataPaneStatusText.set("异常");
    }

    public TableView<RoleVo> RoleTableView;
    public ObservableList<RoleVo> dataPaneObservableList = FXCollections.observableArrayList();
    public BooleanProperty selectAllBooleanProperty = new SimpleBooleanProperty(false);
    private HBox createDataPane() {
        CheckBox selectAll = new CheckBox();
        selectAll.selectedProperty().bindBidirectional(selectAllBooleanProperty);
        selectAll.setOnAction(
            e -> RoleTableView.getItems().forEach(
                item -> item.setSelected(selectAllBooleanProperty.get())
            )
        );
        Label placeholderLabel = new Label();
        placeholderLabel.textProperty().bind(dataPaneStatusText);

        TableColumn<RoleVo, Boolean> selectCol = new TableColumn<>();
        TableColumn<RoleVo, String> RolenameCol = new TableColumn<>("角色名");
        TableColumn<RoleVo, String> permissionCol = new TableColumn<>("权限");

        selectCol.setGraphic(selectAll);
        selectCol.setSortable(false);
        selectCol.setCellValueFactory(c -> c.getValue().selectedProperty());
        selectCol.setCellFactory(CheckBoxTableCell.forTableColumn(selectCol));
        selectCol.setEditable(true);
        selectCol.setPrefWidth(37);
        selectCol.setMinWidth(37);
        selectCol.setMaxWidth(37);
        RolenameCol.setCellValueFactory(cellData -> cellData.getValue().nameProperty());
        permissionCol.setCellValueFactory(cellData -> cellData.getValue().passwordProperty());

        RoleTableView = new TableView<>();
        RoleTableView.setEditable(true);
        RoleTableView.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY_FLEX_LAST_COLUMN);
        RoleTableView.getColumns().addAll(selectCol, RolenameCol, permissionCol);
        RoleTableView.setPlaceholder(placeholderLabel);
        RoleTableView.setItems(dataPaneObservableList);
        HBox.setHgrow(RoleTableView, Priority.ALWAYS);
        HBox dataTable = new HBox(RoleTableView);
        dataTable.setPadding(new Insets(0, 0, 3, 0));
        VBox.setVgrow(dataTable, Priority.ALWAYS);
        return dataTable;
    }

    private Pagination pagination;
    public IntegerProperty pageSizeProperty = new SimpleIntegerProperty(100);
    public IntegerProperty currentPageIndexProperty = new SimpleIntegerProperty(0);
    public IntegerProperty pageCountProperty = new SimpleIntegerProperty(1);
    public IntegerProperty maxPageIndicatorCount = new SimpleIntegerProperty(1);
    public ChangeListener<Number> numberChangeListener = (obs, oldIndex, newIndex) -> {
        selectAllBooleanProperty.set(false);
        new RoleListQueryController(this).startAsyncQuery();
    };
    public HBox createPagePane() {
        pagination = new Pagination();
        pagination.setStyle("-fx-page-information-alignment:right;");
        pagination.pageCountProperty().bind(pageCountProperty);
        pagination.maxPageIndicatorCountProperty().bind(maxPageIndicatorCount);
        pagination.currentPageIndexProperty().bindBidirectional(currentPageIndexProperty);
        pagination.currentPageIndexProperty().addListener(numberChangeListener);
        HBox.setHgrow(pagination, Priority.ALWAYS);
        HBox pagePane = new HBox(pagination);
        return pagePane;
    }

}


